package org.marlin.http;

import org.marlin.http.annotation.HttpClient;
import org.marlin.http.annotation.HttpScan;
import org.marlin.http.proxy.HttpFactoryBean;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

/**
 * init version 1.5.0
 * @author Jack ZG
 * @since 1.0.0
 */
public class HttpScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {
    private static final Logger log = LoggerFactory.getLogger(HttpScannerRegistrar.class);

    private ResourceLoader resourceLoader;


    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(HttpScan.class.getName()));
        ClassPathHttpScanner scanner = new ClassPathHttpScanner(registry);
        if (this.resourceLoader != null) {
            scanner.setResourceLoader(this.resourceLoader);
        }
        Class<? extends HttpFactoryBean> httpFactoryBeanClass = null;
        if (annoAttrs != null) {
            httpFactoryBeanClass = annoAttrs.getClass("factoryBean");
        }
        if (HttpFactoryBean.class.equals(httpFactoryBeanClass)) {
            HttpFactoryBean<?> mapperFactoryBean = (HttpFactoryBean) BeanUtils.instantiateClass(httpFactoryBeanClass);
            scanner.setMapperFactoryBean(mapperFactoryBean);
        }

        List<String> basePackages = new ArrayList<>();

        String[] basePackageArr = annoAttrs.getStringArray("basePackages");
        for (int i = 0; i < basePackageArr.length; i++) {
            String pkg = basePackageArr[i];
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }

        scanner.setAnnotationClass((Class) HttpClient.class);
        String[] httpHandlerRefs = annoAttrs.getStringArray("httpHandlerRef");
        scanner.setHttpHandlerBeanNames(httpHandlerRefs);

        log.info("@HttpScan====basePackages:" + Arrays.toString((Object[]) basePackageArr) + ",httpHandlerRef: " + annoAttrs.getStringArray("httpHandlerRef"));

        scanner.registerFilters();

        scanner.doScan(StringUtils.toStringArray(basePackages));
    }


    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
}

